<?php

namespace App\Console\Commands\ChatGroup;

use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupSessionAppraiseModel;
use App\Models\Shop\ShopModel;
use App\Service\OpenShop\User\RmsUserService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use SebastianBergmann\CodeCoverage\Report\PHP;

class exportChatGroupHistory extends Command
{
    /**
     * The name and signature of the console command.
     * startTime Ymd
     * @var string
     */
    protected $signature = 'chatGroup:export-chat-group-history {--startTime=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导出群聊历史消息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        @ini_set('memory_limit', '1024M');

        // 参数校验
        $startTime = $this->option('startTime');
        if ($startTime && strlen($startTime) != 8) {
            $this->error('时间格式不正确，请输入 Ymd 的时间格式');
            die();
        }

        $list = [];
        ChatGroupHistoryModel::query()
            ->when($startTime, function ($q) use ($startTime) {
                $q->where('createdAt', '>=', Carbon::createFromFormat('Ymd', $startTime)->startOfDay()->timestamp);
            })
            ->whereIn('type', [ChatGroupHistoryModel::TYPE_TEXT, ChatGroupHistoryModel::TYPE_DIALOG, ChatGroupHistoryModel::TYPE_APPRAISE])
            ->select('shopId', 'content', 'createdAt', 'sessionId', 'senderUid', 'type')
            ->chunk(100, function ($history) use (&$list){
                foreach ($history as $item) {
                    echo '.';
                    $shop = Cache::store('array')->remember('shop:'. $item->shopId, 1200, function () use ($item) {
                        $model = ShopModel::query()->find($item->shopId);
                        return $model->shopCode . '-'. $model->name;
                    });

                    switch ($item->type) {
                        case ChatGroupHistoryModel::TYPE_TEXT:
                            $content = $item->content;
                            break;
                        case ChatGroupHistoryModel::TYPE_DIALOG:
                            // 获得卡片标题
                            $title   = json_decode($item->content, true)['title'] ?? '-';
                            $content = '答案卡：' . $title;
                            break;
                        case ChatGroupHistoryModel::TYPE_APPRAISE:
                            $content = '';
                            // 根据用户ID和sessionId获得评价内容
                            $userIds  = collect(json_decode($item->content, true))->pluck('user_id');

                            // 获得评价详情
                            $appraiseInfo = [];
                            ChatGroupSessionAppraiseModel::query()
                                ->whereIn('uid', $userIds)
                                ->where('sessionId', $item->sessionId)
                                ->select(['score', 'solve', 'uid'])
                                ->get()
                                ->map(function (ChatGroupSessionAppraiseModel $chatGroupSessionAppraiseModel) use (&$appraiseInfo) {
                                    $appraiseInfo[$chatGroupSessionAppraiseModel->uid] = '评分：' . ($chatGroupSessionAppraiseModel->score ? ($chatGroupSessionAppraiseModel->score . '分') : '未评分 ') . '    是否解决：' . ($chatGroupSessionAppraiseModel->solve ? ChatGroupSessionAppraiseModel::SOLVE_MAPPING[$chatGroupSessionAppraiseModel->solve] : '未选择');
                                })->toArray();

                            foreach ($userIds as $userId) {

                                $username = self::getUserName($userId);

                                if (isset($appraiseInfo[$userId])) {
                                    $content .= "【{$username}】" . $appraiseInfo[$userId] . PHP_EOL;
                                } else {
                                    $content .= "【{$username}】未评价" . PHP_EOL;
                                }
                            }

                            break;
                        default:
                            $content = '';
                    }

                    $list[] = [
                        $item->sessionId,
                        $shop,
                        self::getUserName( $item->senderUid),
                        $content,
                        $item->createdAt->toDateTimeString(),
                    ];
                }
            });

        $this->export(['会话id', '门店', '发送人', '内容', '时间'], $list);
    }

    public static function getUserName($userId)
    {
        return Cache::store('array')->remember('user:'. $userId, 1200, function () use ($userId){
            return RmsUserService::getRmsUserInfoByUserIds([$userId])['data'][0]['username'] ?? '';
        });
    }

    public function export(array $headers, array $data)
    {
        // UTF8的BOM头
        $path = sys_get_temp_dir() . '/' . Str::random() . '.csv';
        $fd   = fopen($path, 'w+');
        fwrite($fd, "\xEF\xBB\xBF");

        // 表头
        if ($headers) {
            fputcsv($fd, $headers);
        }

        collect($data)->each(function ($item) use (&$fd) {
            fputcsv($fd, $item);
        });


        if (is_resource($fd)) {
            fclose($fd);
        }

        dump($path);

        $detailUrl = FileUtil::uploadFile($path, 'csv',
            "tmp/" . date('Ymd') . '/' . Str::uuid() . '.csv')['url'];
        dump($detailUrl);
    }
}
